<template>
  <el-select
    :model-value="value"
    v-bind="{ ...attr }"
    filterable
    remote
    reserve-keyword
    placeholder="请输入内容"
    :remote-method="remoteMethod"
    :loading="loading"
    :collapse-tags="true"
    :collapse-tags-tooltip="true"
    @change="changeHandle"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</template>

<script setup>
import { getTeacherByName } from 'api/common'
import { watch } from 'vue'
import { uniqBy } from 'lodash-es'

const props = defineProps({
  modelValue: [String, Number, Array],
  attr: {
    type: Object,
    default: () => {
      return { placeholder: '请选择' }
    }
  },

  formItem: {
    type: Object
  }
})

const options = ref([])
const loading = ref(false)
const emit = defineEmits(['update:modelValue', 'change'])
const value = ref('')
const cacheArr = ref([])

watch(() => props.modelValue, val => {
  value.value = val
  if (props.attr.teacherName) {
    getTeacherByName({ name: props.attr.teacherName }).then(res => {
      options.value = res.result
    }).finally(() => {
      loading.value = false
    })
  }
})

function changeHandle(e) {
  emit('update:modelValue', e)
  // const temp = []
  // e.forEach(item => {
  //   const obj = options.value.find(v => item === v.id)
  //   if (obj) {
  //     temp.push({
  //       id: item,
  //       name: obj.name
  //     })
  //   }
  // })
  // cacheArr.value = cacheArr.value.concat(temp)
  // cacheArr.value = cacheArr.value.filter(item => e.includes(item.id))
  // cacheArr.value = uniqBy(cacheArr.value, 'id')
  // emit('change', { key: props.formItem.field, data: cacheArr.value })
}

const remoteMethod = query => {
  if (query) {
    loading.value = true
    getTeacherByName({ name: query }).then(res => {
      options.value = res.result
    }).finally(() => {
      loading.value = false
    })
  } else {
    options.value = []
  }
}
</script>
